import {Component, OnDestroy, OnInit} from '@angular/core';
import {ExtendHttpService} from '../../../common/extend-http.service';
import {TipService} from '../../services/tip.service';
import {ActivatedRoute, Router} from '@angular/router';
import {SocketService} from '../../services/socket.service';

declare let layer;

@Component({
  selector: 'app-order-details',
  templateUrl: './order-details.component.html',
  styleUrls: ['./order-details.component.css']
})
export class OrderDetailsComponent implements OnInit, OnDestroy {

  unWsMessage: any; // websocket通讯对象
  payTypeList: any = []; // 支付方式列表-（系统）
  paymentId: any = ''; // 选择的支付方式-（系统）
  payOrderType: any = ''; // 支付方式
  paySysNo: any = ''; // 收银员工主键
  out_trade_no: any = ''; // 当前银行订单号

  remark = ''; // 备注

  realMoney: any = 0; // 实收
  is_smear_zero: any = ''; // 0否 1是
  smearZero: any = '0'; // 抹零规则

  discountList: any = []; // 折扣列表
  checkedDiscount: any = {}; // 选择的折扣


  // 餐桌设置列表显示/隐藏
  tableSet = false;

  // 菜品设置的显示/隐藏
  foodSet = false;

  // 订单列表
  orderList = [];

  // 提示信息类型
  tipType = 'error';

  // 餐桌id
  tid = '';

  // 总数量
  countNumber = 0;

  // 总价格
  countPrice = 0;

  // 餐桌分类名称
  tableClass = '';

  // 已下单的餐桌名称
  tableName = '';

  // 订单id
  orderId = '';

  // 订单流水号
  orderNum = '';

  // 下单人
  orderUser = '';

  // 下单时间
  orderTime = '';

  // 用餐人数
  people_num: any = 0;

  scrollTop = 0;

  constructor(
    private extendHttp: ExtendHttpService,
    private tipService: TipService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private socketService: SocketService,
  ) {

    this.activatedRoute.queryParams.subscribe(param => {
      this.tid = param['tid'];
      // this.tableClass = param['tableClass'];
      // this.tableName = param['tableName'];
      this.scrollTop = param['scrollTop'];
    });
  }

  ngOnInit() {

    cBack = () => {
      $('#btn-back').trigger('click');
    };

    this.extendHttp.post('/merchantApp/singleprocess/findOrderByTid', {tid: this.tid}).subscribe(response => {
      let data = response.json();
      if (data.code === '0') {
        this.orderId = data.orderForm.id;
        this.orderNum = data.orderForm.order_id;
        this.orderList = data.orderForm.detailList;
        this.orderUser = data.orderForm.create_user_name;
        this.orderTime = data.orderForm.order_time;
        this.people_num = data.orderForm.people_num;
        // 桌子信息
        this.tableClass = data.orderForm.tableClassName;
        this.tableName = data.orderForm.table_name;
        this.orderList.forEach((v) => {
          this.countNumber += v.num;
          this.countPrice += v.total_price;
          this.realMoney = this.countPrice.toFixed(2);
        });
      } else if (data.code == '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, '登录超时，跳转到登录页面');
        setTimeout(() => {
          this.router.navigate(['/login']);
        }, 1000);
      } else {
        this.tipType = 'error';
        this.tipService.change(true, data.message);
      }
    }, error => {
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });

    // $('#app-page').height('100%');
    this.qiangzhiHenpin();

    // Listen for orientation changes
    window.addEventListener('orientationchange', () => {
      // Announce the new orientation number
      setTimeout(() => {
        // alert(window.orientation);
        this.qiangzhiHenpin();
      }, 200);
    }, false);

    // 订阅websocket消息
    this.unWsMessage = this.socketService.wsMessage.subscribe(res => {
      console.log(res, '快餐模式下单台接收消息');
      if (res.code === '1011') {
        console.log(res);
        if (this.out_trade_no === res.backOrderNo) {
          layer.msg(res.message);
          this.testPay('');
        }
      }
    });

    this.getPaySysNo();
    this.getDiscount();
    this.getPayTypeList();
  }

  // 获取员工主键
  getPaySysNo() {
    this.extendHttp.get('/merchantApp/getpaycode/xypaycode/getMerchantUserNo', {}).subscribe(res => {
      if (res.json().code === '0') {
        this.paySysNo = res.json().userNo;
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
      }
    });
  }

  // 计算器
  calc() {
    this.realMoney = this.countPrice;
  }

  // 获取折扣列表
  getDiscount() {
    // discountList
    this.extendHttp.get('/merchantApp/operationgTable/Settlement/getDiscount', {}).subscribe(res => {
      if (res.json().code === '0') {
        this.discountList = res.json().list;
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
      }
    });
  }

  // 选择折扣
  checkDiscountClick(v) {
    if (v.id === this.checkedDiscount.id) {
      this.checkedDiscount = {};
      this.realMoney = this.countPrice.toFixed(2);
      // this.choosePayList[0].money = this.realMoney;
      return;
    }
    this.checkedDiscount = v;
    this.realMoney = ((this.countPrice * v.discount_num) * 1).toFixed(2);
    // this.choosePayList[0].money = this.realMoney;

    this.is_smear_zero = '';
  }

  // 获取支付方式
  getPayTypeList() {
    this.extendHttp.post('/merchantApp/operationgTable/Settlement/findAllByMid', {}).subscribe(res => {
      if (res.json().code === '0') {
        this.payTypeList = res.json().paymentList;
        this.payTypeList.forEach(item => {
          this.payTypeList[item.name] = item.id;
        });
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
      }
    });
  }

  // 是否开启抹零
  open1() {
    this.is_smear_zero = this.is_smear_zero === '0' ? '1' : '0';
    if (this.is_smear_zero) {
      this.handpart();
    } else {
      this.calc();
    }
  }

  // 抹零
  handpart() {
    this.is_smear_zero = this.is_smear_zero === '1' ? '' : '1';
    if (this.smearZero === '0') { // 按元抹零
      this.realMoney = (Math.floor(this.countPrice / 10) * 10).toFixed(2);
    }
    if (this.smearZero === '1') { // 按角抹零
      this.realMoney = Math.floor(this.countPrice).toFixed(2);
    }
    if (!this.is_smear_zero) {
      this.realMoney = this.countPrice.toFixed(2);
    }
    // this.choosePayList[0].money = this.realMoney;

    this.checkedDiscount = {};
  }

  // 使用扫码枪
  openScanBox() {
    if (!this.paySysNo) {
      layer.msg('登录人未绑定收银');
      return;
    }
    if (!this.realMoney || this.realMoney < 0) {
      layer.msg('请输入不小于0的金额');
      return;
    }
    layer.open({
      type: 1,
      title: false,
      btn: false,
      // shadeClose: true,
      content: $('.scan-box'),
      icon: 1,
      area: ['500px', ''],
      // offset: ['25%', ''],
      success: () => {
        this.payOrderType = '';
        document.onkeydown = (e) => {
          $('#payCodeFocus').focus();
        };
      },
      cancel: () => {
        // layer.msg('关闭');
        $('.scan-box').hide();
      }
    });
  }

  // 获取支付二维码
  openQrCode(num) {
    layer.msg('暂未开通');
    if (!this.paySysNo) {
      layer.msg('登录人未绑定收银');
      return;
    }
    if (!this.realMoney || this.realMoney < 0) {
      layer.msg('请输入不小于0的金额');
      return;
    }
    let url = num === '102' ? '/merchantApp/getpaycode/xypaycode/getWxCode' : '/merchantApp/getpaycode/xypaycode/aliPayCode';
    this.payOrderType = num;
    let index = layer.load(2, {time: 10 * 1000});
    this.extendHttp.get(url, {
      'total_fee': this.realMoney,
      // 'total_fee': this.cartPrice,
      'systemUserSysNo': this.paySysNo,
    }).subscribe(res => {
      layer.close(index);
      if (res.json().code === '0') {
        this.out_trade_no = res.json().out_trade_no;
        // let src = num === '102' ? res.json().wxurl : res.json().code_url;
        let src = res.json().code_img_url;
        layer.open({
          type: 1,
          title: false,
          btn: false,
          // shadeClose: true,
          content: '<div style="padding: 5px;">' +
          '<div style="text-align: center;">支付二维码</div>' +
          '<div id="code" style="text-align: center;"><img src="' + src + '" alt=""></div>' +
          '</div>' +
          '<style>#code table{margin: 0 auto;}</style>',
          icon: 1,
          area: ['400px', ''],
          offset: ['5%', ''],
          success: () => {
            // $('#code').qrcode({
            //   render: 'table', // table方式
            //   width: 200, // 宽度
            //   height: 200, // 高度
            //   text: src // 任意内容
            // });
          },
          cancel: () => {
            // layer.msg('关闭');
          }
        });
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
        this.out_trade_no = '';
      }
    });
  }

  // 测试支付
  testPay(payCode) {
    // console.log('金额：' + payCode.value, '号码：' + payCode.value);
    let paymentId = this.payOrderType ? this.payOrderType === '103' ? this.payTypeList['支付宝'] : this.payTypeList['微信支付'] : this.payTypeList['扫码枪'];
    let obj = {
      'orderId': this.orderId,
      'remark': this.remark,
      'is_smear_zero': this.is_smear_zero,
      'smear_money': this.is_smear_zero === '1' ? (this.countPrice - this.realMoney) : '',
      'discount_money': this.realMoney,
      'payJson': JSON.stringify([{
        paymentId: paymentId,
        money: this.realMoney
      }]),
      'Auth_Code': payCode ? payCode.value : '',
      'Old_SysNo': this.paySysNo,
      'orderType': this.payOrderType ? this.payOrderType : payCode.value.substring(0, 2) > 15 ? '103' : '102',
      'paymentId': paymentId,
      'out_trade_no': this.out_trade_no,

      'is_credit': '0',
      'creditPeoPle': '',
      'is_entertain': '0',
      'entertain': '',
      'is_free': '0',
      'free_remark': '',
    };
    // console.log(obj);
    let index = layer.load(2, {time: 10 * 1000});
    this.extendHttp.post('/merchantApp/operationgTable/Settlement/settlementOrder', obj).subscribe(res => {
      // console.log(res);
      if (payCode) {
        payCode.value = '';
      }
      layer.closeAll();
      $('.scan-box').hide();
      if (res.json().code === '0') {
        layer.msg(res.json().message);
        this.paySuccessDeal();
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
      }
    });
  }

  // 测试支付2
  testPay2(payCode) {
    // console.log('金额：' + money.value, '号码：' + payCode.value);
    let obj = {
      'orderId': this.orderId,
      'remark': this.remark,
      'is_smear_zero': this.is_smear_zero,
      'smear_money': this.is_smear_zero === '1' ? (this.countPrice - this.realMoney) : '',
      'discount_money': this.realMoney,
      'payJson': JSON.stringify([{
        paymentId: this.payTypeList['现金'],
        money: this.realMoney
      }]),
      'Auth_Code': payCode ? payCode.value : '',
      'Old_SysNo': this.paySysNo,
      'orderType': this.payOrderType || '',
      'paymentId': this.payTypeList['现金'],
      'out_trade_no': this.out_trade_no,

      'is_credit': '0',
      'creditPeoPle': '',
      'is_entertain': '0',
      'entertain': '',
      'is_free': '0',
      'free_remark': '',
    };
    // console.log(obj);
    let index = layer.load(2, {time: 10 * 1000});
    this.extendHttp.post('/merchantApp/operationgTable/Settlement/settlementOrder', obj).subscribe(res => {
      // console.log(res);
      if (payCode) {
        payCode.value = '';
      }
      layer.closeAll();
      $('.scan-box').hide();
      if (res.json().code === '0') {
        layer.msg(res.json().message);
        this.paySuccessDeal();
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
      }
    });
  }

  // 是否显示餐桌设置列表
  changTable() {
    // this.tableSet = !this.tableSet;
  }

  // 是否显示菜品的设置列表
  changeFood() {
    // this.foodSet = !this.foodSet;
  }

  // 结算订单
  payOrder() {

    let arr = [];
    let cardId = '';

    let obj = {
      'orderId': this.orderId,
      'remark': this.remark,
      'payJson': JSON.stringify(arr),
      'cardId': '',
      'is_free': '0',
      'free_remark': '',
      'is_entertain': '0',
      'entertain': '',
      'is_credit': '0',
      'creditPeoPle': '',
      'isCardCode': '0',
      'code': '',
      'is_accounting': '0',
      'discount_money': this.countPrice,
      'is_smear_zero': this.is_smear_zero, // 是否抹零 0 否  1 是
      'smear_money': this.countPrice - this.realMoney, // 抹零金额
      'is_discount': this.checkedDiscount.id ? '1' : '0', // 是否折扣 0否 1是
      'discount_id': this.checkedDiscount.id ? this.checkedDiscount.id : '', // 折扣id
    };
    let index = layer.load(2);
    this.extendHttp.post('/merchant/operationgTable/Settlement/settlementOrder', obj).subscribe(res => {
      layer.close(index);
      if (res.json().code === '0') {
        layer.msg(res.json().message);
        this.router.navigateByUrl('index/operation/checkstand');
      } else {
        layer.msg(this.extendHttp.errTips(res.json()));
      }
    });
  }

  // 开台成功处理-清空订单数据
  paySuccessDeal() {
    setTimeout(() => {
      this.router.navigate(['/login']);
    }, 1000);
  }

  // 竖屏设置强制横屏
  qiangzhiHenpin() {
    let width = document.documentElement.clientWidth;
    let height = document.documentElement.clientHeight;
    if (width < height) {
      // console.log(width + ' ' + height);
      // alert(width);
      let $print = $('#print');
      $print.width(height);
      $print.height(width);
      $print.css('top', (height - width) / 2);
      $print.css('left', 0 - (height - width) / 2);
      $print.css('transform', 'rotate(-90deg)');
      $print.css('transform-origin', '50% 50%');
    } else {
      let $print = $('#print');
      $print.width(width);
      $print.height(height);
      $print.css('top', 0);
      $print.css('left', 0);
      $print.css('transform', 'none');
      $print.css('transform-origin', '50% 50%');
    }

    let evt = 'onorientationchange' in window ? 'orientationchange' : 'resize';

    window.addEventListener(evt, function () {
      console.log(evt);
      let width = document.documentElement.clientWidth;
      let height = document.documentElement.clientHeight;
      let $print = $('#print');
      if (width > height) {
        $print.width(width);
        $print.height(height);
        $print.css('top', 0);
        $print.css('left', 0);
        $print.css('transform', 'none');
        $print.css('transform-origin', '50% 50%');
      } else {
        $print.width(height);
        $print.height(width);
        $print.css('top', (height - width) / 2);
        $print.css('left', 0 - (height - width) / 2);
        $print.css('transform', 'rotate(-90deg)');
        $print.css('transform-origin', '50% 50%');
      }

    }, false);
  }

  ngOnDestroy() {
    this.unWsMessage.unsubscribe();
  }

}
